package com.zhinong.aop;

import com.zhinong.annotation.SelectCache;
import com.zhinong.dto.PageQueryDTO;
import com.zhinong.result.PageResult;
import com.zhinong.result.Result;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

@Aspect
@Component
@Slf4j
public class SelectCacheAspect {

    @Autowired
    private RedisTemplate redisTemplate;

    @Pointcut("@annotation(com.zhinong.annotation.SelectCache)")
    public void selectCachePointCut(){}

    

    @Around("selectCachePointCut()")
    public Result<PageResult> selectPage(ProceedingJoinPoint joinPoint) throws Throwable {
        log.info("进入缓存切面");
        //获取拦截参数
        Object[] args = joinPoint.getArgs();
        PageQueryDTO pageQueryDTO = (PageQueryDTO) args[0];

        //构建redis查询key
        MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
        SelectCache annotation = methodSignature.getMethod().getAnnotation(SelectCache.class);
        String selectKey = annotation.name() + pageQueryDTO.getPage()+pageQueryDTO.getPageSize();

        //进行查询
        PageResult pageResult = (PageResult) redisTemplate.opsForValue().get(selectKey);

        //缓存命中
        if(pageResult!=null){
            log.info("缓存命中");
            return Result.success(pageResult);
        }
        //缓存未命中
        log.info("缓存未命中");

        //执行原来的方法
        Result<PageResult> result = (Result<PageResult>) joinPoint.proceed();

        //写入缓存
        redisTemplate.opsForValue().set(selectKey,result.getData());

        return result;
    }
}

